package com.mixi.feedreader;

import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.zip.Inflater;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;

import com.mixi.feedreader.FeedCollection.Feed;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.FeatureInfo;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.test.PerformanceTestCase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.RemoteViews.ActionException;
import android.widget.Toast;

public class FeedReaderActivity extends Activity implements IController {
    /** Called when the activity is first created. */
	public static final String tag = "mixi";
	public static int cnt = 0;
	public static int current = 0;
	public int currentPublisherIndex = 1;
	public static ArrayList<Holder> hList;
	public static String publisherString = "",categoryString="";
	public final static String headTitle = "MIXI-News :: ";
	
	
	private FeedCollection feedCollection;
	private ImageButton publisherBtn;
	private TextView titleTx;
	
	private String currentURL = "http://www.voanews.com/templates/Articles.rss?sectionPath=/thai/news/economy-business";
	
	
	public ListView lsx,cateList;
	
	SharedPreferences prefMan;
	SharedPreferences.Editor prefEditor;
	//private Adapter currentAdaper
	
	
	
	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        titleTx = (TextView)findViewById(R.id.textView1);
        titleTx.setText(headTitle);
        
        prefMan = PreferenceManager.getDefaultSharedPreferences(this);
        prefEditor = prefMan.edit();
        

        if( (prefMan.getString("deviceId", "")).equals("") ){
        
        	String deviceId = Settings.System.getString(getContentResolver(),
                    Settings.System.ANDROID_ID);
        	prefEditor.putString("deviceId", deviceId);
        	prefEditor.commit();
        	
        	
        	
//        	Toast.makeText(FeedReaderActivity.this, "Recording Device ID"+deviceId.length(), Toast.LENGTH_LONG).show();
        }
        
        
        String requestCode = generateRequestCode(extractID(prefMan.getString("deviceId", "")));
    	prefEditor.putString("requestCode", partitioningString(requestCode));
    	prefEditor.commit();
        
        
        
        if(!isUnlocked()){
//        	Intent activateDialog = new Intent(this,activateApps);
        	final String activationCode = extractID(prefMan.getString("deviceId",""));
        	
        	 AlertDialog.Builder alert = new AlertDialog.Builder(this); 
        	 alert.setCancelable(false); 
        	 alert.setTitle("Unlock MIXI Application");  
        	 alert.setMessage("Request Code : " +prefMan.getString("requestCode", "Error!")+
        	 		"\nEnter Activate Code :"/*+activationCode*/);                
        	 
//        	 final String activationCode = extractID(prefMan.getString("activationCode",""));

        	  // Set an EditText view to get user input   
        	  final EditText input = new EditText(this); 
        	  alert.setView(input);

        	     alert.setPositiveButton("Acitvate", new DialogInterface.OnClickListener() {  
        	     public void onClick(DialogInterface dialog, int whichButton) {  
        	         String value = input.getText().toString();
        	         if(value.length()>8){
        	        	value = extractActivationCode(value);
        	         }
        	         
        	         	if(value.equals("mixi2012")||value.equals(activationCode)){
        	         		
        	         		prefEditor.putBoolean("activationStatus", true);
        	         		prefEditor.commit();
        	         		Toast.makeText(FeedReaderActivity.this, "Activation successful", Toast.LENGTH_SHORT).show();
        	         		dialog.dismiss();
        	         		
        	         	}else if(value.equals("deactivate")){
        	         		
        	         		prefEditor.putBoolean("activationStatus", false);
        	         		prefEditor.commit();
        	         		Toast.makeText(FeedReaderActivity.this, "Application deactivated", Toast.LENGTH_SHORT).show();
        	         		dialog.dismiss();
        	    
        	         	}else{
        	         		AlertDialog.Builder dx = new AlertDialog.Builder(FeedReaderActivity.this);
        	         		dx.setTitle("Activation fail!");dx.setCancelable(false); 
        	         		dx.setMessage("Incorrect activation code , please check your activation code or \ncontact MIXI customer services.");
        	         		dx.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
								
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									finish();
									
								}
							});
        	         		dx.show();
        	         		
        	         		
        	         		
        	         	}
        	         return;                  
        	        }  
        	      });  

        	     alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {

        	         public void onClick(DialogInterface dialog, int which) {
        	             // TODO Auto-generated method stub
        	        	 finish();
        	             return;   
        	         }
        	     });
        	             alert.show();
        	
        }
        
        Intent callSplash = new Intent(FeedReaderActivity.this,Splash.class);
		startActivity(callSplash);
        
        feedCollection = new FeedCollection();
        
        lsx = (ListView) findViewById(R.id.listView1);
        cateList = (ListView) findViewById(R.id.cateList);//= new ListView(this);
        
        publisherBtn = (ImageButton)findViewById(R.id.publisher_btn);
        publisherBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent callPublisher = new Intent(FeedReaderActivity.this,Publisher.class);
				startActivityForResult(callPublisher, 101);// Assume 101 as publisherCall code
			}
		});
        
        
//        ArrayList<Feed> fx = feedCollection.getList();
//        for(Feed fn:fx){
//        	Log.i(tag, "\n====================================\n");
//        	Log.i(tag, fn.getId()+"");
//        	Log.i(tag, fn.getPublisher());
//        	
//        	for(String lnk: fn.getCateURL() ){
//        		String word[] = lnk.split("\\|");  
//        		Log.i(tag, word[0]+" :: "+word[1]);
//            }
//        }
        
//        refreshCurrentURL();
//        if(!isUnlocked())return;
        
        refreshScreen(currentPublisherIndex,0);
        //setContentView(tx);
        publisherBtn.setImageResource(FeedCollection.PUBLISHER_LOGO[currentPublisherIndex-1]);
        ArrayList<String> cateListString = feedCollection.getList().get(currentPublisherIndex-1).getCateURL();
		cateList.setAdapter(new CateAdapter(FeedReaderActivity.this, cateListString,this));
        
        lsx.setAdapter(new NewsAdapter(this,hList));
        
        
        
        
        
        //-- Web Advertising
        
        final WebView webview = (WebView)findViewById(R.id.webView1);
        webview.getSettings().setJavaScriptEnabled(true);  
        
        /* WebViewClient must be set BEFORE calling loadUrl! */  
        webview.setWebViewClient(new WebViewClient() {  
            @Override  
            public void onPageFinished(WebView view, String url)  
            {  
                webview.loadUrl("javascript:(function() { " +  
                        "document.getElementsByTagName('body')[0].style.color = 'red'; " +  
                        "})()");  
            }  
        });  
          
        webview.loadUrl("http://mixi.co.th/mixi_banner.php");  
        
//        webview.loadUrl("http://www.lcdtvthailand.com/asp-bin/pic_webboard/mixi_Himedia.gif");
        webview.setClickable(true);
        webview.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				Intent ix = new Intent(Intent.ACTION_VIEW);
				ix.setData(Uri.parse("http://www.mixi.co.th"));
				startActivity(ix);
			}
		});
        
        
//        String pref = prefMan.getString("value", "got nothing");
        
        
//        String deviceId = Settings.System.getString(getContentResolver(),
//                Settings.System.ANDROID_ID);
        

//        String uid ="";// tManager.getDeviceId();
//        
//        String serialnum = "";
//        try {                                                                               
//        	Class<?> c = Class.forName("android.os.SystemProperties");        	 
//        	Method get = c.getMethod("get", String.class, String.class );                     
//        	serialnum = (String)(   get.invoke(c, "ro.serialno", "unknown" )  );     
//        	Toast.makeText(this, "OK :: "+serialnum+" DvID :: "+deviceId+" UID :: "+uid+" pref :: "+pref, Toast.LENGTH_LONG).show();
//        }                                                                                 
//        catch (Exception ignored)                                                         
//        {   
//        	Toast.makeText(this, "NOT OK :: "+serialnum+" DvID :: "+deviceId+"UID :: "+uid+" pref :: "+pref, Toast.LENGTH_LONG).show();
//        }
        
        
    }


    private boolean isUnlocked(){
    	return prefMan.getBoolean("activationStatus", false);
    }
    
    private String extractID(String input){
    	String key = "";
    	if(input.length()==16){
    	key+=input.charAt(0);
    	key+=input.charAt(1);
    	key+=input.charAt(input.length()-2);
    	key+=input.charAt(input.length()-1);
    	}
    	return key;
    }
    
    private String extractActivationCode(String input){
    	String key = "";
    	if(input.length()==16){
    		key+=input.charAt(0);
        	key+=input.charAt(12);
        	key+=input.charAt(4);
        	key+=input.charAt(8);
    	}
    	return key;
    }
//    
    private String generateRequestCode(String key){
		
    	String output ="";
    	if(key.length()<4)return output;
    	
    	Random myRandom = new Random();
    	
    	while(output.length()<16){
    		int n = myRandom.nextInt();
    		if(n<0)n*=-1;
    		output += String.valueOf(n);
    		
    		Log.i("xct", n+"");
    	}
    	
    	char[] nx = output.toCharArray();
    	nx[3]=key.charAt(0);
    	nx[15]=key.charAt(1);
    	nx[7]=key.charAt(2);
    	nx[11]=key.charAt(3);
    	//output = nx.toString();
    	output="";
    	for(int i=0;i<16;i++){
    		output+=nx[i];
    	}
    	Log.i("xct", output);
    	return output;
    }
    
    
    private String partitioningString(String key){
		String output="";
		
		char[] nx = key.toCharArray();
		
		for(int i=0;i<key.length();i++){
			output+=nx[i];
			if((i+1)%4==0 && i!=15){
				output+=" - ";
			}
		}

    	return output;
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
    	super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 101)
			if(resultCode == RESULT_OK){
				if(data!=null)
//				Toast.makeText(FeedReaderActivity.this
//						, "Select "+data.getExtras().getString("code")
//						, Toast.LENGTH_SHORT).show();
					currentPublisherIndex = Integer.parseInt(data.getExtras().getString("code"));
					//TODO :: Change button Image
					publisherBtn.setImageResource(FeedCollection.PUBLISHER_LOGO[currentPublisherIndex-1]);
				
					//TODO :: Draw category list
					ArrayList<String> cateListString = feedCollection.getList().get(currentPublisherIndex-1).getCateURL();
				
					cateList.setAdapter(new CateAdapter(FeedReaderActivity.this, cateListString,this));
					//TODO :: Set adapter listener
//					cateList.setClickable(true);
//					cateList.setOnItemClickListener(new OnItemClickListener() {
//
//						public void onItemClick(AdapterView<?> arg0, View arg1,
//								int arg2, long arg3) {
////							Log.i(tag, arg2+" :: "+arg3)
//							Log.i(tag, "xxx");
//						}
//					});
					
					refreshScreen(currentPublisherIndex,0);
			}
	}
    

    private void refreshScreen(int publisherIndex,int categoryIndex){
    	if(publisherIndex>feedCollection.getList().size()){
    		Log.i(tag, " >> none publisher ");
    		return;
    	}
    	
    	Feed fn = feedCollection.getList().get(publisherIndex-1);

    	String word[] = (fn.getCateURL().get(categoryIndex)).split("\\|");
    	
    	currentURL = word[1];
    	Log.i(tag, word[1]);
    	
    	publisherString = " "+fn.getPublisher();
    	categoryString = " "+word[0];
    	
    	titleTx.setText(headTitle+publisherString+" >> "+categoryString);
    	refreshCurrentURL();
    	lsx.setAdapter(new NewsAdapter(this,hList));
    	
    }
    
    private void refreshCurrentURL() {
		try{
        	
        	hList = new ArrayList<Holder>();
        	URL feed = new URL(currentURL);
        	SAXParserFactory spf = SAXParserFactory.newInstance();
        	SAXParser sp = spf.newSAXParser();
        	
        	XMLReader xr = sp.getXMLReader();
        	TagHandler th = new TagHandler();
        	xr.setContentHandler(th);
        	
        	xr.parse(new InputSource(feed.openStream()));
        	ParsedTag ptlist = th.getParseTag();
        	
        	
        	ptlist.getExtractedString();
//        	tx.setText(ptlist.getExtractedString());
        	
        	String test ="";
        	for(Holder item : hList){
        		String temp = item.getTitle()+"\n";
        		temp+=item.getLink()+"\n";
        		temp+=item.getDescription()+"\n";
        		temp+="===========\n";
        		test+=temp;
        	}
        	//tx.setText(test+"x");
        	
        	
        	
        }catch (Exception e) {
			Log.i(tag, " :: "+e.getMessage());
        	e.printStackTrace();
		}
	}
    
    
    
    
    
    
    
    
    
    
    
    
    public class CateAdapter extends BaseAdapter{

    	private ArrayList<String> list;
    	private Context parentContext;
    	private LayoutInflater inflater;
    	public IController Ictrl;
    	public CateAdapter(Context context,ArrayList<String> listx,IController ctrlx){
    		list = listx;
    		parentContext = context;
    		Ictrl =ctrlx;
    		Log.i(FeedReaderActivity.tag,"Category Adapter constructed "+list.size());
    		inflater = (LayoutInflater) parentContext.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    	}
    	
		public int getCount() {
			return list.size();
		}

		public String getItem(int arg0) {
			return list.get(arg0);
		}

		public long getItemId(int arg0) {
			return arg0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			ItemHolder item;
			final int pos = position;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.cate_list_item, null, false);
				item = new ItemHolder();
				item.title = (TextView) convertView.findViewById(R.id.title_tx);
				convertView.setTag(item);
			}else{
				item = (ItemHolder) convertView.getTag();
			}
			
			String word[] = (this.getItem(position)).split("\\|");
			item.title.setText(word[0]);
			item.id = pos;
			
			
			convertView.setOnClickListener(new OnClickListener() {
				
				public void onClick(View arg0) {
					
					Log.i(tag, " >> Click >>"+pos);
					Ictrl.msg(pos+"");
					
				}
			});
			
			return convertView;
			
			
		}
		
		public class ItemHolder{
	    	public TextView title;
	    	public int id;
	    }
    	
    }
    
    
    
    
    
    
    public class NewsAdapter extends BaseAdapter{

    	ArrayList<Holder> currentList;
    	Context parentContext;
    	LayoutInflater inflater;
    	
    	
    	public NewsAdapter(Context context,ArrayList<Holder> list){
    		currentList = list;
    		Log.i(FeedReaderActivity.tag,"News Adapter constructed "+list.size());
    		parentContext = context;
    		//inflater = (LayoutInflater) parentContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    		inflater = (LayoutInflater) parentContext.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    	}
    	
		public int getCount() {
			Log.i(FeedReaderActivity.tag, "call getCout"+currentList.size());
			return currentList.size();
		}

		public Object getItem(int position) {
			return currentList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
//			Log.i(FeedReaderActivity.tag, "call getView");
			ItemHolder item;
			final int pos = position;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.list_item, null, false);
				item = new ItemHolder();
				item.title = (TextView) convertView.findViewById(R.id.title_tx);
				item.description = (TextView) convertView.findViewById(R.id.description_tx);
				item.link = (ImageButton) convertView.findViewById(R.id.link_btn);
				
				convertView.setTag(item);
			}else{
				item = (ItemHolder) convertView.getTag();
			}
			
			item.title.setText(((Holder)this.getItem(position)).title);
			
			String des = ((Holder)this.getItem(position)).description;
			Log.i("xct", "image tag"+des.indexOf("<img"));
			if(des.length()<4 || (des.indexOf("<img"))>-1 )des = "";
			item.description.setText(des);
			
			item.link.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					startIntentForId(pos);
				}
			});
			
//			mark
			item.link.setImageResource(R.drawable.btn_webview);
			
//			Log.i(FeedReaderActivity.tag, " Assemble "+position);
			return convertView;
		}
		
		
		private void startIntentForId(int id){
			String url = ((Holder)this.getItem(id)).link;
			Log.i(FeedReaderActivity.tag, "Click on"+url);
			
			Intent ix = new Intent(Intent.ACTION_VIEW);
			ix.setData(Uri.parse(url));
			startActivity(ix);
			
		}
		
		public class ItemHolder{
	    	public TextView title;
	    	public TextView description;
	    	public ImageButton link;
	    }
    	
    }






	public String msg(String input) {
		Log.i(tag, "I Controller Actived");
		refreshScreen(currentPublisherIndex,Integer.parseInt(input));
		return null;
	}
    
    
}